package com.soulmate.auth.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 拒绝用户访问
 * @author huaiping
 */
@Component
@AllArgsConstructor
public class UserAuthAccessDeniedHandler implements AccessDeniedHandler {
    private ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        String resp = objectMapper.writeValueAsString(ResponseEntity.status(HttpStatus.FORBIDDEN).body("拒绝访问"));
        response.getWriter().write(resp);
    }
}
